package utils

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"strings"
)

func CheckNecessaryQuery(necessaryQueries []string, c *gin.Context) bool {
	var (
		query string
	)
	for _, query = range necessaryQueries {
		if c.Query(query) == "" {
			return false
		}
	}
	return true
}
func CheckNecessaryCookie(necessaryCookies []string, c *gin.Context) bool {
	var (
		cookie string
		err error
	)
	for _, cookie = range necessaryCookies {
		if _,err = c.Cookie(cookie);err != nil{
			return false
		}
	}
	return true
}
func CheckNecessaryForm(necessaryForms []string, c *gin.Context) bool {
	var (
		dataStr []byte
		form string
		data map[string]interface{}
		err  error
		ok   bool
	)
	data = make(map[string]interface{})
	dataStr,_ = c.GetRawData()
	if err = jsoniter.Unmarshal(dataStr,&data); err != nil {
		return false
	}
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(dataStr))
	for _, form = range necessaryForms {
		if _, ok = data[form]; !ok {
			return false
		}
	}
	return true
}
func CheckCaptcha(client *redis.Client,c *gin.Context,inputCaptcha string)bool{
	var (
		SessionId,
		captcha string
		err error
	)
	SessionId,_ = c.Cookie("SessionId")
	if captcha,err = client.HGet("captchaCache",SessionId).Result();err != nil || captcha == ""{
		c.JSON(200, gin.H{
			"pass": false,
			"msg":  "验证码过期",
		})
		return false
	}else{
		if captcha != strings.ToLower(inputCaptcha){
			c.JSON(200, gin.H{
				"pass": false,
				"msg":  "验证码错误",
			})
			return false
		}else{
			client.HDel("captchaCache",SessionId)
			return true
		}
	}
}
